<template>
    <div class="app-container">
        <el-form :model="searchForm" inline ref="searchForm" style="position:relative;">
            <el-row>
                <el-col :span="20">
                    <el-form-item label="预约类型：" prop="reservationType">
                        <el-select clearable v-model="searchForm.reservationType" placeholder="请选择">
                            <el-option v-for="item in reservationTypeOpt" :key="item.value" :label="item.name" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="预约状态：" prop="reservationStatus">
                        <el-select clearable v-model="searchForm.reservationStatus" placeholder="请选择">
                            <el-option v-for="item in reservationStatusOpt" :key="item.value" :label="item.name" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-button type="primary" @click="init('search')" >查询</el-button>
                </el-col>
                <el-col :span="4">
                    <el-button @click="addClick" type="primary" style="position: absolute;right: 0;">新建预约</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="tableData" border style="width: 100%;margin: 20px 0;">
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column prop="districtName" label="所在区域" align="center"></el-table-column>
            <el-table-column prop="serviceName" label="所需服务" align="center"></el-table-column>
            <el-table-column prop="merchantName" label="商户" align="center"></el-table-column>
            <el-table-column prop="userAddressLinkman" label="联系人" align="center"></el-table-column>
            <el-table-column prop="userAddressPhone" label="联系电话" align="center" width="108"></el-table-column>
            <el-table-column prop="userAddressDetail" label="详细地址" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="reservationTime" label="预约时间" align="center" width="160"></el-table-column>
            <el-table-column prop="reservationStatus" :formatter="reservationStatusFun" label="预约状态" align="center"></el-table-column>
            <el-table-column prop="reservationType" :formatter="reservationTypeFun" label="预约类型" align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" width="160"></el-table-column>
            <el-table-column label="操作" width="160" fixed="right" align="center">
                <template slot-scope="scope">
                    <el-button @click.stop="editClick(scope.row)" type="primary" :disabled="scope.row.reservationStatus == 3 || scope.row.reservationStatus == 4" plain size="mini">编辑</el-button>
                    <el-button @click.stop="detailClick(scope.row.id)" plain size="mini">详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @current-change="getList" layout="total, prev, pager, next, jumper" :total="pageData.totalElements"></el-pagination>
        <!-- 弹框 -->
        <el-dialog :title="nowTit" :visible.sync="showDialog" width="800px">
            <el-tabs type="border-card" v-model="actived">
                <el-tab-pane label="基本信息" name="1">
                    <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left" label-width="100px" style="margin: 0px 50px;">
                        <el-form-item label="所在区域：" prop="userAddressDistrictId">
                            <el-cascader clearable :options="districtList" :disabled="popStatus == 1 || popStatus == 3" placeholder="必选项。请选择所在区域" :props="optionProps" @change="getMerchant" v-model="userAddressDistrictId" change-on-select style="width: 100%;"></el-cascader>
                        </el-form-item>
                        <el-form-item label="服务类型：" prop="serviceCategoryId">
                            <el-cascader clearable :options="serviceCategoryOpt" :disabled="popStatus == 1 || popStatus == 3" placeholder="必选项。请选择服务类型" :props="optionProps" v-model="serviceCategoryId" change-on-select @change="handleChange" style="width: 100%"></el-cascader>
                        </el-form-item>
                        <el-form-item label="所需服务：" prop="serviceId">
                            <el-select v-model="dataForm.serviceId" placeholder="必选项。请选择所需服务（请先选择服务类型）" :disabled="popStatus == 1 || popStatus == 3" @change="getMerchant" style="width: 100%">
                                <el-option v-for="item in serviceOpt" :key="item.id" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="商户：" prop="merchantId">
                            <el-input v-model="merchantName" disabled placeholder="必填项。（请先选择所在区域和所需服务）"></el-input>
                        </el-form-item>
                        <el-form-item label="联系人：" prop="userAddressLinkman">
                            <el-input v-model="dataForm.userAddressLinkman" :disabled="popStatus == 1 || popStatus == 3" placeholder="必选项。请输入联系人，长度为1-20位" maxlength="20"></el-input>
                        </el-form-item>
                        <el-form-item label="联系电话：" prop="userAddressPhone">
                            <el-input v-model="dataForm.userAddressPhone" :disabled="popStatus == 1 || popStatus == 3" maxlength="11" placeholder="必选项。请输入联系电话"></el-input>
                        </el-form-item>
                        <el-form-item label="详细地址：" prop="userAddressDetail">
                            <el-input v-model="dataForm.userAddressDetail" :disabled="popStatus == 1 || popStatus == 3" placeholder="必选项。请输入详细地址，长度为1-100位" maxlength="100"></el-input>
                        </el-form-item>
                        <el-form-item label="预约时间：" prop="reservationTime">
                            <el-date-picker v-model="dataForm.reservationTime" :disabled="popStatus == 1 || popStatus == 3" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="必选项。请选择预约时间" style="width: 100%"></el-date-picker>
                        </el-form-item>
                        <el-form-item label="预约备注：" prop="reservationRemark">
                            <el-input v-model="dataForm.reservationRemark" :disabled="popStatus == 3" type="textarea" :rows="4" placeholder="请输入预约备注，长度为1-200位" maxlength="200"></el-input>
                        </el-form-item>
                        <el-form-item v-show="popStatus != 3">
                            <el-button @click="saveClick('dataForm')" type="primary">保存</el-button>
                            <el-button @click="cancelClick('dataForm')">取消</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="过程" name="2" v-if="popStatus == 3"></el-tab-pane>
                <el-tab-pane label="回访" name="3" v-if="popStatus == 3">
                    <el-button @click="addReservationCallback" type="primary" style="">新建回访</el-button>
                    <el-table :data="reservationCallbackList" border style="width: 100%;margin: 20px 0;">
                        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
                        <el-table-column prop="callBackTime" label="回访时间" align="center" width="160"></el-table-column>
                        <el-table-column prop="description" label="回访描述" align="center"></el-table-column>
                        <el-table-column prop="createTime" label="创建时间" align="center" width="160"></el-table-column>
                    </el-table>
                    <!-- 分页 -->
                    <el-pagination @current-change="callbackGetList" layout="total, prev, pager, next, jumper" :total="callbackPageData.totalElements"></el-pagination>
                    <!-- 弹框 -->
                    <el-dialog :visible.sync="reservationCallbackshowDialog" width="800px" append-to-body>
                        <el-form ref="reservationCallbackForm" :rules="reservationCallbackRules" :model="reservationCallbackForm" label-position="left" label-width="100px" style="margin: 0px 50px;">
                            <el-form-item label="回访时间：" prop="callBackTime">
                                <el-date-picker v-model="reservationCallbackForm.callBackTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="必选项。请选择回访时间" style="width: 100%"></el-date-picker>
                            </el-form-item>
                            <el-form-item label="回访描述：" prop="description">
                                <el-input v-model="reservationCallbackForm.description" type="textarea" :rows="4" placeholder="请输入回访描述"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button @click="saveCallbackClick('reservationCallbackForm')" type="primary">保存</el-button>
                                <el-button @click="cancelClick('reservationCallbackForm')">取消</el-button>
                            </el-form-item>
                        </el-form>
                    </el-dialog>
                </el-tab-pane>
                <el-tab-pane label="投诉" name="4" v-if="popStatus == 3">
                    <el-table :data="reservationComplaintList" border style="width: 100%;margin: 20px 0;">
                        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
                        <el-table-column prop="description" label="投诉描述" align="center"></el-table-column>
                        <el-table-column prop="createTime" label="创建时间" align="center" width="160"></el-table-column>
                    </el-table>
                    <!-- 分页 -->
                    <el-pagination @current-change="complaintGetList" layout="total, prev, pager, next, jumper" :total="complaintPageData.totalElements"></el-pagination>
                </el-tab-pane>
                <el-tab-pane label="评价" name="5" v-if="popStatus == 3">
                    <el-form ref="evaluation" :model="evaluation" label-position="left" label-width="100px" style="margin: 0px 50px;">
                        <el-form-item label="用户：" prop="sysUserName">
                            <el-input v-model="evaluation.sysUserName" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="用户评分：" prop="userScore">
                            <el-rate v-model="evaluation.userScore" disabled show-score text-color="#ff9900"></el-rate>
                        </el-form-item>
                        <el-form-item label="用户评价：" prop="userEvaluation">
                            <el-input v-model="evaluation.userEvaluation" disabled type="textarea" :rows="4"></el-input>
                        </el-form-item>
                        <el-form-item label="评价晒图：" prop="userEvaluationImage">
                            <img :src="evaluation.userEvaluationImage" width="180" alt="">
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
    </div>
</template>
<script>
import { addReservation, addCallback, findReservation, findCallback, findComplaint, detailReservation, editReservation, editRemark, delReservation } from '@/api/reservations/reservation'
import { getReservationId } from '@/api/reservations/reservation-evaluation'
import { findServiceCategory } from '@/api/service/service-category'
import { findService } from '@/api/service/customize-service-level'
import { findDistrictAllRegion } from '@/api/system/district-module/region'
import { getMerchartRecord } from '@/api/service-provider/merchant'
import { getCookie, setCookie } from '@/utils/auth'
import { isvalidPhone } from '@/utils/validate'
import { uploadPic, getPic } from '@/api/uploadPic'
export default {
    name: 'Reservation',
    data() {
         const validatePhone = (rule, value, callback) => {
            if (value) {
                if (!isvalidPhone(value)) {
                callback(new Error('手机号为11位数字，如18688889999'))
                }else{
                callback()
                }
            } else {
                callback(new Error('请输入手机号'))
            }
        }
        return{
            searchForm: {
                reservationNo: '',
                reservationType: '',
                reservationStatus: '',
            },
            reservationTypeOpt: [
                {value: '1', name: '系统代约'},
                {value: '2', name: '用户网约'}
            ],
            reservationStatusOpt: [
                {value: '1', name: '待服务'},
                {value: '2', name: '服务中'},
                {value: '3', name: '服务完成'},
                {value: '4', name: '未完成'}
            ],
            tableData: [],
            nowTit: '',
            showDialog: false,
            dataForm: {
                reservationRemark: '',
                reservationTime: '',
                serviceId: '',
                serviceName: '',
                merchantId: '',
                userAddressDetail: '',
                userAddressDistrictId: '',
                userAddressLinkman: '',
                userAddressPhone: '',
                reservationType: 1,
                reservationStatus: 1,
                sysUserId: getCookie('pid'),
            },
            rules: {
                reservationTime: [
                    { required: true, message: '请选择预约时间', trigger: 'change' }
                ],
                serviceId: [
                    { required: true, message: '请选择所需服务', trigger: 'change' }
                ],
                merchantId: [
                    { required: true, message: '请选择商户', trigger: 'change' }
                ],
                userAddressDetail: [
                    { required: true, message: '请输入详细地址', trigger: 'blur' }
                ],
                userAddressLinkman: [
                    { required: true, message: '请输入联系人', trigger: 'blur' }
                ],
                userAddressPhone: [
                    {  trigger: 'blur', validator: validatePhone }
                ],
            },
            userAddressDistrictId: [],
            serviceCategoryId: [],
            serviceCategoryOpt: [],
            optionProps: {
                value: 'id',
                label: 'name',
                children: 'children'
            },
            pageData: {},
            nowId: '',
            nowPage: 0,
            pageSize: 10,
            callbackNowPage: 0,
            callbackPageSize: 10,
            complaintNowPage: 0,
            complaintPageSize: 10,
            serviceOpt: [],
            districtList: [],
            merchantName: '',
            popStatus: 0,
            actived: '1',
            reservationCallbackshowDialog: false,
            reservationCallbackForm: {
                callBackTime: '',
                description: ''
            },
            reservationCallbackRules: {
                time: [
                    { required: true, message: '请选择回访时间', trigger: 'change' }
                ],
                description: [
                    { required: true, message: '请输入回访描述', trigger: 'blur' }
                ],
            },
            reservationCallbackList: [],
            reservationComplaintList: [],
            evaluation: {},
            callbackPageData: {},
            callbackData: {},
            complaintPageData: {},
            complaintData: {},
        }
    },
    methods: {
        //默认函数
        init(params){
            const _this = this;
            if(params == 'search'){
                _this.nowPage = 0
            }
            //获取列表信息
            findReservation( _this.nowPage, _this.pageSize, _this.searchForm.reservationNo, _this.searchForm.reservationType, _this.searchForm.reservationStatus ).then(response => {
                if(response.code == 200){
                    _this.pageData = response.object;
                    _this.tableData = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //服务分类
        serviceCategoryList(){
            const _this = this;
            //获取列表信息
            findServiceCategory(0, 10000).then(response => {
                if(response.code == 200){
                    _this.serviceCategoryOpt = _this.getTreeData(response.object.content);
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //区域
        districtFun(){
            const _this = this;
            //获取列表信息
            findDistrictAllRegion().then(response => {
                if(response.code == 200){
                    _this.districtList = _this.getTreeData(response.object);
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //递归
        getTreeData(data){
            for(var i=0;i<data.length;i++){
                if((data[i].children == null) || (data[i].children.length<1)){
                    data[i].children=undefined;
                }else {
                    this.getTreeData(data[i].children);
                }
            }
            return data;
        },
        //商户（加盟商）
        Merchant(){
            const _this = this;
            _this.merchantName = '';
            _this.dataForm.merchantId = '';
            //获取商户
            let did = '';
            if(this.userAddressDistrictId.length > 0){
                did = this.userAddressDistrictId[this.userAddressDistrictId.length - 1];
            }
            getMerchartRecord(did, this.dataForm.serviceId).then(response => {
                if(response.code == 200){
                    _this.merchantName = response.object.companyName;
                    _this.dataForm.merchantId = response.object.id;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //获取商户
        getMerchant(){
            if((this.userAddressDistrictId.length != 0) && this.dataForm.serviceId){
                let obj = {};
                obj = this.serviceOpt.find((item)=>{
                    return item.id === this.dataForm.serviceId;
                });
                this.dataForm.serviceName = obj.name;
                this.Merchant();
            }
        },
        addClick(){
            this.popStatus = 0;
            this.showDialog = true;
            this.dataForm.reservationRemark = '';
            this.dataForm.reservationTime = '';
            this.serviceCategoryId = [];
            this.dataForm.serviceId = '';
            this.dataForm.merchantId = '';
            this.dataForm.userAddressDetail = '';
            this.dataForm.userAddressDistrictId = '';
            this.userAddressDistrictId = [];
            this.dataForm.userAddressLinkman = '';
            this.dataForm.userAddressPhone = '';
            if(this.dataForm.id){
                delete this.dataForm.id;
            }
        },
        //编辑
        editClick(row){
            this.popStatus = 1;
            this.nowId = row.id;
            this.actived = '1';
            detailReservation(row.id).then(response => {
                if(response.code == 200){
                    this.dataForm.reservationRemark = response.object.reservationRemark;
                    this.dataForm.reservationTime = response.object.reservationTime;
                    this.serviceCategoryId = [];
                    if(response.object.serviceCategoryList){
                        for(let i=0;i<response.object.serviceCategoryList.length;i++){
                            this.serviceCategoryId.push(response.object.serviceCategoryList[i].id);
                        }
                    }
                    this.handleChange(this.serviceCategoryId);
                    this.dataForm.serviceId = response.object.serviceId;
                    this.dataForm.merchantId = response.object.merchantId;
                    this.dataForm.userAddressDetail = response.object.userAddressDetail;
                    this.dataForm.userAddressDistrictId = response.object.userAddressDistrictId;
                    this.userAddressDistrictId = [];
                    this.merchantName = response.object.merchantName;
                    if(response.object.districtList){
                        for(let i=0;i<response.object.districtList.length;i++){
                            this.userAddressDistrictId.push(response.object.districtList[i].id);
                        }
                    }
                    this.dataForm.userAddressLinkman = response.object.userAddressLinkman;
                    this.dataForm.userAddressPhone = response.object.userAddressPhone;
                }else{
                    this.$message.error(response.message);
                }
            })
            this.showDialog = true;
        },
        //详情
        detailClick(rowId){
            this.popStatus = 3;
            this.nowId = rowId;
            this.callbackList();
            this.complaintList();
            this.getReservationFun(rowId)
            detailReservation(rowId).then(response => {
                if(response.code == 200){
                    this.dataForm.reservationRemark = response.object.reservationRemark;
                    this.dataForm.reservationTime = response.object.reservationTime;
                    this.serviceCategoryId = [];
                    if(response.object.serviceCategoryList){
                        for(let i=0;i<response.object.serviceCategoryList.length;i++){
                            this.serviceCategoryId.push(response.object.serviceCategoryList[i].id);
                        }
                    }
                    this.handleChange(this.serviceCategoryId);
                    this.dataForm.serviceId = response.object.serviceId;
                    this.dataForm.merchantId = response.object.merchantId;
                    this.dataForm.userAddressDetail = response.object.userAddressDetail;
                    this.dataForm.userAddressDistrictId = response.object.userAddressDistrictId;
                    this.userAddressDistrictId = [];
                    this.merchantName = response.object.merchantName;
                    if(response.object.districtList){
                        for(let i=0;i<response.object.districtList.length;i++){
                            this.userAddressDistrictId.push(response.object.districtList[i].id);
                        }
                    }
                    this.dataForm.userAddressLinkman = response.object.userAddressLinkman;
                    this.dataForm.userAddressPhone = response.object.userAddressPhone;
                }else{
                    this.$message.error(response.message);
                }
            })
            this.showDialog = true;
        },
        //保存
        saveClick(formName){
            let _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //提交
                    if(this.userAddressDistrictId.length == 0){
                        this.$message.warning('请选择所在区域');
                        return false
                    }
                    _this.dataForm.userAddressDistrictId = this.userAddressDistrictId[this.userAddressDistrictId.length - 1];
                    if(_this.popStatus == 0){  //添加
                        addReservation(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })

                    }else if(_this.popStatus == 1){  //修改
                        const obj = {}
                        obj.id = _this.nowId;
                        obj.reservationRemark = _this.dataForm.reservationRemark;
                        editRemark(obj).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }
                    
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //保存回访
        saveCallbackClick(formName){
            let _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //提交
                    _this.reservationCallbackForm.reservationId = this.nowId;
                    addCallback(_this.reservationCallbackForm).then(response => {
                        if(response.code == 200){
                            this.$message.success(response.message);
                            _this.callbackList();
                            _this.reservationCallbackshowDialog = false;
                        }else{
                            this.$message.error(response.message);
                        }
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            })
        },
        //取消
        cancelClick(formName){
            this.showDialog = false;
            this.reservationCallbackshowDialog = false;
            this.$refs[formName].resetFields();
        },
        //分页
        getList(val) {
            this.nowPage = val - 1;
            this.init();
        },
        handleChange(value) {
            const _this = this;
            this.dataForm.serviceId = '';
            let sid = '';
            if(value.length > 0){
                sid = value[value.length - 1];
            }
            //获取列表信息
            findService(0, 10000,sid).then(response => {
                if(response.code == 200){
                    _this.serviceOpt = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        reservationStatusFun(row){
            if(row.reservationStatus == 1){
                return '待服务'
            }else if(row.reservationStatus == 2){
                return '服务中'
            }else if(row.reservationStatus == 3){
                return '服务完成'
            }else if(row.reservationStatus == 4){
                return '未完成'
            }
        },
        reservationTypeFun(row){
            if(row.reservationType == 1){
                return '系统代约'
            }else if(row.reservationType == 2){
                return '用户网约'
            }
        },
        addReservationCallback(){
            this.reservationCallbackshowDialog = true
        },
        // 预约回访
        callbackList(){
            const _this = this
            //获取列表信息
            findCallback( _this.callbackNowPage, _this.callbackPageSize, _this.nowId ).then(response => {
                if(response.code == 200){
                    _this.callbackPageData = response.object;
                    _this.callbackData = response.object.content;
                    this.reservationCallbackList = response.object.content
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        // 分页
        callbackGetList(val) {
            this.callbackNowPage = val - 1;
            this.callbackList();
        },
        // 预约投诉
        complaintList(){
            const _this = this
            //获取列表信息
            findComplaint( _this.complaintNowPage, _this.complaintPageSize, _this.nowId ).then(response => {
                if(response.code == 200){
                    _this.complaintPageData = response.object;
                    _this.complaintData = response.object.content;
                    this.reservationComplaintList = response.object.content
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        // 分页
        complaintGetList(val) {
            this.complaintNowPage = val - 1;
            this.complaintList();
        },
        // 预约评价
        getReservationFun(id){
            const _this = this
            //获取信息
            getReservationId( id ).then(response => {
                if(response.code == 200){
                    _this.evaluation.sysUserName = response.object.nickName
                    _this.evaluation.userScore = response.object.userScore
                    _this.evaluation.userEvaluation = response.object.userEvaluation
                    _this.evaluation.userEvaluationImage = response.object.userEvaluationImage
                    // if(response.object.userEvaluationImage){
                    //     getPic(response.object.userEvaluationImage).then(res => {
                    //         if(res.code == 200){
                    //             _this.evaluation.userEvaluationImage = res.object
                    //         }else{
                    //             this.$message.error(res.message)
                    //         }
                    //     })
                    // }else{
                    //     response.object.userEvaluationImage = ''
                    // }
                    
                }else{
                    this.$message.error(response.message);
                }
            })
        },
    },
    mounted(){
        this.init();
        this.serviceCategoryList();
        this.districtFun();
    }
}
</script>
